package com.rickpan.utils;

import com.rickpan.security.UserDetailsServiceImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;

/**
 * 安全工具类
 */
public class SecurityUtils {

    /**
     * 获取当前认证的用户
     */
    public static UserDetailsServiceImpl.UserPrincipal getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsServiceImpl.UserPrincipal) {
            return (UserDetailsServiceImpl.UserPrincipal) authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        UserDetailsServiceImpl.UserPrincipal user = getCurrentUser();
        if (user != null) {
            return user.getId();
        }

        // 检查是否为开发环境
        String profile = System.getProperty("spring.profiles.active", "dev");
        if ("dev".equals(profile) || "development".equals(profile)) {
            // 开发环境：使用默认用户ID，但记录详细日志
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth instanceof AnonymousAuthenticationToken) {
                System.out.println("⚠️ 开发环境：检测到匿名用户访问，使用默认用户ID=4");
                System.out.println("   认证状态: " + auth.getClass().getSimpleName());
                System.out.println("   建议：为API请求添加JWT认证头");
            } else {
                System.out.println("⚠️ 开发环境：认证用户为null，使用默认用户ID=4");
                System.out.println("   认证状态: " + (auth != null ? auth.toString() : "null"));
            }
            return 4L;
        } else {
            // 生产环境：抛出异常，绝不允许默认用户
            throw new RuntimeException("生产环境无法获取当前用户ID，认证失败！");
        }
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        UserDetailsServiceImpl.UserPrincipal user = getCurrentUser();
        return user != null ? user.getUsername() : null;
    }

    /**
     * 检查当前用户是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() 
               && !"anonymousUser".equals(authentication.getPrincipal());
    }

    /**
     * 检查当前用户是否有指定角色
     */
    public static boolean hasRole(String role) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getAuthorities().stream()
                    .anyMatch(authority -> authority.getAuthority().equals("ROLE_" + role));
        }
        return false;
    }

    /**
     * 检查当前用户是否是管理员
     */
    public static boolean isAdmin() {
        return hasRole("ADMIN");
    }

    /**
     * 检查当前用户是否是普通用户
     */
    public static boolean isUser() {
        return hasRole("USER");
    }
}
